package com.qf.commons.web.utils;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.UUID;

public class UploadUtils implements WebMvcConfigurer {

    //源文件名
    private String originalFilename;

    //源文件后缀名
    private String suffix;

    //存入数据库里的tomcat虚拟路径
    private String dbPath;

    //文件大小
    private long size;

    //实际存储路径
    private String realPath;

    public  boolean doUpload(MultipartFile attach, HttpServletRequest request,String uploader){
        if (!attach.isEmpty()){
            originalFilename = attach.getOriginalFilename();
            System.out.println("===>上传的文件名："+originalFilename);

            suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            System.out.println("===>文件后缀名" + suffix);

            size = attach.getSize();
            System.out.println("===>上传的文件大小"+size);

            String currentFilename = System.currentTimeMillis()+ UUID.randomUUID().toString()+suffix;
            System.out.println("====>存储的上传文件名："+currentFilename);
            realPath = "D:/image/"+uploader;
            System.out.println("=====>上传保存的真实路径"+realPath);

            File targetFile = new File(realPath+currentFilename);
            if (!targetFile.exists()){
                targetFile.mkdirs();
            }

            try {
                attach.transferTo(targetFile);
            }catch (Exception e){
                e.printStackTrace();
                return false;
            }
            realPath = realPath + "/" + currentFilename;

            dbPath = "/" + uploader + "/" + currentFilename;
            return true;
        }else {
            return false;
        }
    }

    public String getUploadFile(){
        return dbPath;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        /**
         * addResourceHandler:指的是对外暴露的访问路径
         * addResourceLocations：指的是内部文件放置的目录
         */
        registry.addResourceHandler("/upload/**").addResourceLocations("file:D:/upload");
    }
}
